import 'package:flutter/material.dart';

class AnimationListPage extends StatefulWidget {
  const AnimationListPage({Key? key}) : super(key: key);

  @override
  _AnimationListPageState createState() => _AnimationListPageState();
}

class _AnimationListPageState extends State<AnimationListPage> {
  final GlobalKey<AnimatedListState> _animatedListGlobalKey =
      GlobalKey<AnimatedListState>();

  List<String> _list = [];

  @override
  void initState() {
    super.initState();

    _list = List.generate(3, (index) => '第 $index 条').toList();
  }

  Widget _widgetItem(index) {
    return ListTile(
      title: Text('第 $index 条'),
      trailing: IconButton(
        onPressed: () {
          _deleteItem(index);
        },
        icon: const Icon(Icons.delete),
      ),
    );
  }

  _addItem() {
    _list.add('第 ${_list.length} 条');
    _animatedListGlobalKey.currentState!.insertItem(
      _list.length - 1,
      duration: const Duration(milliseconds: 500),
    );
  }

  _deleteItem(index) {
    _list.removeAt(index);
    _animatedListGlobalKey.currentState!.removeItem(index,
        (context, animation) {
      return ScaleTransition(
        scale: animation,
        child: _widgetItem(index),
      );
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        IconButton(
          onPressed: _addItem,
          icon: const Icon(Icons.add),
        ),
        Expanded(
          flex: 1,
          child: AnimatedList(
            key: _animatedListGlobalKey,
            initialItemCount: _list.length,
            itemBuilder: (context, index, animation) {
              return FadeTransition(
                opacity: animation,
                child: _widgetItem(index),
              );
            },
          ),
        ),
      ],
    );
  }
}
